package test;

import java.util.Date;

import com.google.gson.Gson;

import api.SendSmsApi;
import api.SignApi;
import api.SmsDeliverApi;
import api.SmsReportApi;
import api.TemplateApi;
import api.TokenApi;
import beans.ApiResponseSync;
import beans.GetSmsDeliverBean;
import beans.GetSmsDeliverResBean;
import beans.GetSmsReportBean;
import beans.SendSmsBean;
import beans.SendSmsResBean;
import beans.SignsBean;
import beans.SmsTemplateBean;
import beans.SmsTemplateParameterBean;
import beans.TemplateBean;
import beans.TemplateParameterBean;
import beans.TemplatesBean;
import beans.TokenBean;
import helper.DateTimeHelper;
import helper.JsonHelper;
import helper.LogHelper;
import helper.ValidHelper;
import resources.PropertiesLoader;

@SuppressWarnings("unused")
public class MySms {
	private static final String urlString = PropertiesLoader.getConfigValue("urlString");
	private static final String companyNo = PropertiesLoader.getConfigValue("companyNo");
	private static final String loginName = PropertiesLoader.getConfigValue("loginName");
	private static final String privateKey = PropertiesLoader.getConfigValue("privateKey");
	private static TokenBean tokenBean = null;
	private static final LogHelper logger = new LogHelper();
	private static final Gson gson = new Gson();
	
	/**
	 * 短信调用demo
	 * @apiNote 以下9个接口去掉前面注释即可进行测试，测试前请先配置 resources 包下的 config.properties 项目
	 * */
	public static void main(String[] args) throws Exception {
//		RefreshTokenTest();
		GetSignsTest();
//		GetTemplatesTest();
//		SendTemplateSmsTest();
//		SendTemplateSyncTest();
//		SendSmsTest();
//		SendSyncTest();
//		GetSmsReportTest();
//		GetSmsDeliverTest();
	}
	/**
	 * 刷新令牌测试
	 * @throws Exception 
	 * */
	private static void RefreshTokenTest() throws Exception {
		ValidHelper.ValidParams(urlString, companyNo, loginName, privateKey);
		String url = urlString + "/api/user?id=" + companyNo;
		TokenApi api = new TokenApi();
		String res = api.GetToken(url, companyNo, loginName, privateKey);
		tokenBean = JsonHelper.convertFromJsonToObject(res, TokenBean.class);
		String resultStr = gson.toJson(tokenBean);
		System.out.println(resultStr);
	}
	/**
	 * 获取签名列表测试
	 * @throws Exception 参数为空异常
	 * */
	private static void GetSignsTest() throws Exception {
		ValidHelper.ValidParams(urlString, companyNo, loginName, privateKey);
		getToken();
		String url = urlString + "/api/sign";
		SignApi api = new SignApi();
		SignsBean signInfoList = api.GetSigns(url, companyNo, tokenBean.getToken());
		System.out.println(gson.toJson(signInfoList));
		
//		if(signInfoList.getSigns() != null && signInfoList.getSigns().length > 0) {
//			System.out.println("签名列表：");
//			for (int i = 0; i < signInfoList.getSigns().length; i++) {
//				System.out.println("SignId=" + signInfoList.getSigns()[i].getSignId() + " Sign=" + signInfoList.getSigns()[i].getSign());
//			}
//		} else {
//			System.out.println("signInfoList = " + signInfoList.getSigns() + "; 请联系管理员添加签名！");
//		}
	}
	/**
	 * 获取模板列表测试
	 * @throws Exception 参数为空异常
	 * */
	private static void GetTemplatesTest() throws Exception {
		ValidHelper.ValidParams(urlString, companyNo, loginName, privateKey);
		getToken();
		String url = urlString + "/api/template";
		TemplateApi api = new TemplateApi();
		TemplatesBean info = api.GetTemplates(url, companyNo, tokenBean.getToken(), privateKey);
		if(info.getTemplates().length > 0) {
			System.out.println(gson.toJson(info));
//			System.out.println("模板列表：");
//			for (int i = 0; i < info.getTemplates().length; i++) {
//				System.out.println("TemplateId=" + info.getTemplates()[i].getTemplateId() + " TemplateName=" + info.getTemplates()[i].getTemplateName() + " TemplateValue=" + info.getTemplates()[i].getTemplateValue());
//				if(info.getTemplates()[i].getSmsTemplateParameter() != null && info.getTemplates()[i].getSmsTemplateParameter().length > 0) {
//					var params = info.getTemplates()[i].getSmsTemplateParameter();
//					System.out.println("   参数列表：");
//					for(int x = 0; x < params.length; x++) {
//						var paramInfo = params[x];
//						System.out.println("   ParameterId=" + paramInfo.getParameterId() + " ParameterName=" + paramInfo.getParameterName() + " DisplayOrder=" + paramInfo.getDisplayOrder());
//					}
//				}
//			}
		} else {
			System.out.print("请联系管理员添加模板！");
		}
	}
	/**
	 * 同步发送模板短信测试
	 * @throws Exception 
	 * */
	private static void SendTemplateSmsTest() throws Exception {
		ValidHelper.ValidParams(urlString, companyNo, loginName, privateKey);
		getToken();
		String url = urlString + "/api/sms";
		
		// 初始化发送短信实体
		SendSmsBean sendSmsBean = new SendSmsBean();
		sendSmsBean.setCellNumber(new String[] { "18591900000", "18591900001" });
		sendSmsBean.setAppointment(false);
		sendSmsBean.setSignId(25);
		sendSmsBean.setSign("智慧云信");
		
		//分别创建短信参数变量实体
		SmsTemplateParameterBean templateParameter1 = new SmsTemplateParameterBean();
		templateParameter1.setParameterId(1);
		templateParameter1.setParameterValue("2022年7月20日下午2:30");
		
		SmsTemplateParameterBean templateParameter2 = new SmsTemplateParameterBean();
		templateParameter2.setParameterId(2);
		templateParameter2.setParameterValue("20楼第二会议室");
		
		SmsTemplateParameterBean templateParameter3 = new SmsTemplateParameterBean();
		templateParameter3.setParameterId(3);
		templateParameter3.setParameterValue("经营分析会");
		
		SmsTemplateParameterBean templateParameter4 = new SmsTemplateParameterBean();
		templateParameter4.setParameterId(4);
		templateParameter4.setParameterValue("市场部、销售部");
		
		// 创建短信模板
		SmsTemplateBean template = new SmsTemplateBean();
		template.setTemplateId(1);
		template.setTemplateContent("兹定于{datetime}在{room}召开{meetname}会议，请{department}部门负责人参加!");
		// 注意短信模板参数变量实体数组中的元素顺序要与模板内容中变量顺序一致
		template.setSmsTemplateParameterBean(new SmsTemplateParameterBean[] {templateParameter1, templateParameter2, templateParameter3, templateParameter4});
		
		sendSmsBean.setTemplate(template);
		// 此处设置唯一标识，服务端会原样返回，可用于后面获取短信报告进行记录对应
		sendSmsBean.setLinkID(DateTimeHelper.str2TimeStamp(new Date(), "yyyy-MM-dd HH:mm:ss.sss"));
		SendSmsApi api = new SendSmsApi();
		SendSmsResBean resInfo = api.SendSms(url, sendSmsBean, companyNo, tokenBean.getToken()); // 发送模板短信
//		System.out.println(gson.toJson(resInfo));
	}
	/**
	 * 异步发送模板短信测试
	 * @throws Exception
	 * */
	private static void SendTemplateSyncTest() throws Exception{
		ValidHelper.ValidParams(urlString, companyNo, loginName, privateKey);
		getToken();
		String url = urlString + "/api/SendSync";
		
		// 初始化发送短信实体
		SendSmsBean sendSmsBean = new SendSmsBean();
		sendSmsBean.setCellNumber(new String[] { "18591900000", "18591900001" });
		sendSmsBean.setAppointment(false);
		sendSmsBean.setSignId(25);
		sendSmsBean.setSign("智慧云信");
		
		//分别创建短信参数变量实体
		SmsTemplateParameterBean templateParameter1 = new SmsTemplateParameterBean();
		templateParameter1.setParameterId(1);
		templateParameter1.setParameterValue("2022年7月20日下午2:30");
		
		SmsTemplateParameterBean templateParameter2 = new SmsTemplateParameterBean();
		templateParameter2.setParameterId(2);
		templateParameter2.setParameterValue("20楼第二会议室");
		
		SmsTemplateParameterBean templateParameter3 = new SmsTemplateParameterBean();
		templateParameter3.setParameterId(3);
		templateParameter3.setParameterValue("经营分析会");
		
		SmsTemplateParameterBean templateParameter4 = new SmsTemplateParameterBean();
		templateParameter4.setParameterId(4);
		templateParameter4.setParameterValue("市场部、销售部");
		
		// 创建短信模板
		SmsTemplateBean template = new SmsTemplateBean();
		template.setTemplateId(1);
		template.setTemplateContent("兹定于{datetime}在{room}召开{meetname}会议，请{department}部门负责人参加!");
		// 注意短信模板参数变量实体数组中的元素顺序要与模板内容中变量顺序一致
		template.setSmsTemplateParameterBean(new SmsTemplateParameterBean[] {templateParameter1, templateParameter2, templateParameter3, templateParameter4});
		
		sendSmsBean.setTemplate(template);
		// 此处设置唯一标识，服务端会原样返回，可用于后面获取短信报告进行记录对应
		sendSmsBean.setLinkID(DateTimeHelper.str2TimeStamp(new Date(), "yyyy-MM-dd HH:mm:ss.sss"));
		SendSmsApi api = new SendSmsApi();
		ApiResponseSync resInfo = api.SendSync(url, sendSmsBean, companyNo, tokenBean.getToken()); // 发送模板短信
//		System.out.print(gson.toJson(resInfo));
	}
	/**
	 * 同步发送普通短信测试
	 * @throws Exception
	 * */
	private static void SendSmsTest() throws Exception {
		ValidHelper.ValidParams(urlString, companyNo, loginName, privateKey);
		getToken();
		String url = urlString + "/api/sms";
		// 初始化发送短信实体
		SendSmsBean sendSmsBean = new SendSmsBean();
		sendSmsBean.setCellNumber(new String[] { "18591900000", "18591900001" });
		sendSmsBean.setAppointment(false);
		sendSmsBean.setSignId(25);
		sendSmsBean.setSign("智慧云信");
		sendSmsBean.setContent("您的验证码是 837192，五分钟内有效，请勿泄露他人！");
		// 此处设置唯一标识，服务端会原样返回，可用于后面获取短信报告进行记录对应
		sendSmsBean.setLinkID(DateTimeHelper.str2TimeStamp(new Date(), "yyyy-MM-dd HH:mm:ss.sss"));
		SendSmsApi api = new SendSmsApi();
		SendSmsResBean resInfo = api.SendSms(url, sendSmsBean, companyNo, tokenBean.getToken()); // 发送模板短信
//		System.out.print(gson.toJson(resInfo));
	}
	/**
	 * 异步发送普通短信测试
	 * @throws Exception
	 * */
	private static void SendSyncTest() throws Exception{
		ValidHelper.ValidParams(urlString, companyNo, loginName, privateKey);
		getToken();
		String url = urlString + "/api/SendSync";
		// 初始化发送短信实体
		SendSmsBean sendSmsBean = new SendSmsBean();
		sendSmsBean.setCellNumber(new String[] { "18591900000", "18591900001" });
		sendSmsBean.setAppointment(false);
		sendSmsBean.setSignId(25);
		sendSmsBean.setSign("智慧云信");
		sendSmsBean.setContent("您的验证码是 837192，五分钟内有效，请勿泄露他人！");
		// 此处设置唯一标识，服务端会原样返回，可用于后面获取短信报告进行记录对应
		sendSmsBean.setLinkID(DateTimeHelper.str2TimeStamp(new Date(), "yyyy-MM-dd HH:mm:ss.sss"));
		SendSmsApi api = new SendSmsApi();
		ApiResponseSync resInfo = api.SendSync(url, sendSmsBean, companyNo, tokenBean.getToken()); // 发送模板短信
//		System.out.print(gson.toJson(resInfo));
	}
	/**
	 * 查询短信状态测试
	 * @throws Exception 
	 * */
	@SuppressWarnings("unused")
	private static void GetSmsReportTest() throws Exception {
		ValidHelper.ValidParams(urlString, companyNo, loginName, privateKey);
		getToken();
		String url = urlString + "/api/SmsReport";
		var api = new SmsReportApi();
		var getSmsReportBean = new GetSmsReportBean();
		getSmsReportBean.setCompanyNo(companyNo);
		var resInfo = api.GetSmsReport(url, getSmsReportBean, companyNo, tokenBean.getToken());
//		System.out.println(gson.toJson(resInfo));
	}
	/**
	 * 查询上行短信测试
	 * */
	private static void GetSmsDeliverTest() throws Exception {
		ValidHelper.ValidParams(urlString, companyNo, loginName, privateKey);
		getToken();
		String url = urlString + "/api/Delivery";
		var api = new SmsDeliverApi();
		var getSmsDeliverBean = new GetSmsDeliverBean();
		getSmsDeliverBean.setCompanyNo(companyNo);
		var resInfo = api.GetSmsDeliver(url, getSmsDeliverBean, companyNo, tokenBean.getToken());
		
		// 转化接收的时间
//		for (GetSmsDeliverResBean getSmsDeliverResBean : resInfo) {
//			System.out.println(gson.toJson(getSmsDeliverResBean));
//			System.out.println("上行时间：" + DateTimeHelper.getDateFromISO8601DateTimeString(getSmsDeliverResBean.getRecvTime()));	
//		}
	}
	/**
	 * 获取 token
	 * */
	private static void getToken() throws Exception {
		Date nowDate = new Date(System.currentTimeMillis());
		// token 过期，重新获取 token
		if(tokenBean != null) {
			System.out.println(tokenBean.getExpireTime());
			String dt = tokenBean.getExpireTime();
			if(dt != "") {
				dt = dt.replace("T", " ");
				Date nowDt = DateTimeHelper.getDateFromISO8601DateTimeString(dt);
				if(nowDate.compareTo(nowDt) >= 0) {
					RefreshTokenTest();
				}
			}
		} else {
			RefreshTokenTest();
		}
	}
}